package com.ys.service.eKnowAi.impl;

import com.alibaba.fastjson.JSONObject;
import com.ys.config.MyConfig;
import com.ys.entity.eKnowAi.EKnowKnowledgeBase;
import com.ys.entity.eKnowAi.EKnowKnowledgeList;
import com.ys.mapper.eKnowAi.EKnowAiDiySqlMapper;
import com.ys.mapper.eKnowAi.EKnowKnowledgeListMapper;
import com.ys.service.eKnowAi.EKnowKnowledgeListService;

import com.ys.util.SnowflakeIdWorker;
import com.ys.util.baidu.ApiHttpClientUtils;
import com.ys.util.shiro.ShiroUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("eKnowKnowledgeListService")
public class EKnowKnowledgeListServiceImpl implements EKnowKnowledgeListService {
	private static final Logger logger = LoggerFactory.getLogger(EKnowKnowledgeListServiceImpl.class);

	@Autowired
	private EKnowKnowledgeListMapper eKnowKnowledgeListMapper;
	@Autowired
	private EKnowAiDiySqlMapper eKnowAiDiySqlMapper;

	@Autowired
	private ApiHttpClientUtils apiHttpClientUtils;

	private static String URLAPI = MyConfig.getUrlApi1_5();

	@Override
	public int addKnowledgeList(EKnowKnowledgeList eKnowKnowledgeList) {
		int result = eKnowKnowledgeListMapper.insert(eKnowKnowledgeList);
		return result;
	}


	@Override
	public int updateKnowledgeList(EKnowKnowledgeList eKnowKnowledgeList) {
		int result = eKnowKnowledgeListMapper.update(eKnowKnowledgeList);
		return result;
	}

	@Override
	public int deleteKnowledgeList(long id) {
		int result = eKnowAiDiySqlMapper.deleteKnowledgeList(id);
		return result;
	}

	//批量新增知识库
	@Override
	public int addKnowledgeListByList(Map<String, Object> params,String indexName) throws Exception{
		String loginUserId = ShiroUtils.getUserId();//登录的用户ID
		long baseId = Long.parseLong(params.get("baseId").toString());//知识库Id
		long typeId = Long.parseLong(params.get("typeId").toString());//所属分类id
		String information = params.get("information").toString();//内容
		String isRemoveBlank = params.get("isRemoveBlank").toString();//是否去除连续的空格与换行，0否1是
		//分段
		List<String> informationList = splitAndRemoveBlank(information,isRemoveBlank);
		//雪花算法获取id
		SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
		long nextId = idWorker.nextId();
		String sectionId = "eknow_section_"+nextId;
		return sendAdd(baseId,typeId,informationList,loginUserId,indexName,sectionId,null);
	}


	//批量新增知识库
	@Override
	public int addKnowledgeListByList2(long baseId,long typeId,List<String> informationList) throws Exception{
		String loginUserId = ShiroUtils.getUserId();//登录的用户ID

		EKnowKnowledgeBase eKnowKnowledgeBase = new EKnowKnowledgeBase().setId(baseId).queryFirst();
		if(eKnowKnowledgeBase!=null) {
			String indexName = eKnowKnowledgeBase.getESIndexName();//索引名称
			//雪花算法获取id
			SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
			long nextId = idWorker.nextId();
			String sectionId = "eknow_section_"+nextId;
			return sendAdd(baseId,typeId,informationList,loginUserId,indexName,sectionId,null);
		}else {
			return 0;
		}
	}


	//批量新增知识库
	@Override
	public int addKnowledgeListByList3(long baseId,long typeId,List<String> informationList,String sectionId,String infoMark,String loginUserId) throws Exception{
		//String loginUserId = ShiroUtils.getUserId();//登录的用户ID

		EKnowKnowledgeBase eKnowKnowledgeBase = new EKnowKnowledgeBase().setId(baseId).queryFirst();
		if(eKnowKnowledgeBase!=null) {
			String indexName = eKnowKnowledgeBase.getESIndexName();//索引名称
			return sendAddBySection(baseId,typeId,informationList,loginUserId,indexName,sectionId,infoMark);
		}else {
			return 0;
		}
	}


	public int sendAdd(long baseId,long typeId,List<String> informationList,String loginUserId,String indexName,String sectionId,String infoMark) throws Exception{

		EKnowKnowledgeList eKnowKnowledgeList = new EKnowKnowledgeList();
		eKnowKnowledgeList.setUpdateUserId(loginUserId);
		eKnowKnowledgeList.setTypeId(typeId);

		int isSave = 0;

		//接口入参
		Map<String, Object> sendParams = new HashMap<>();
		sendParams.put("indexName",indexName);
		String sentUrl = URLAPI + "/api/outer/baiDuEKnowAi/addKnowledgeListByList";
		//分批向量化,一次16
		int num = 16;
		for(int i=0;i<informationList.size()+num;i=i+num){
			List<String> newlist = informationList.stream().skip(i).limit(num).collect(Collectors.toList());
			sendParams.put("information",newlist);
			//向量数据库新增向量数据接口
			JSONObject addBack = apiHttpClientUtils.sendHttpPost(sendParams,sentUrl);
			logger.info("返回参数："+addBack);
			if(addBack.get("shardIdList")!=null){
				List<String> shardIdList = (List<String>)addBack.get("shardIdList");
				for(int j=0;j<shardIdList.size();j++){
					eKnowKnowledgeList.setInformation(informationList.get(j+i));
					eKnowKnowledgeList.setESId(shardIdList.get(j));
					eKnowKnowledgeList.setStatus(1);
					eKnowKnowledgeList.setBaseId(baseId);
					eKnowKnowledgeList.setSectionId(sectionId);
					if(infoMark!=null && !"".equals(infoMark)){
						eKnowKnowledgeList.setInfoMark(infoMark);
					}
					int thisSave = eKnowKnowledgeListMapper.insert(eKnowKnowledgeList);
					if(thisSave>0) isSave++;
				}
			}
		}
		return isSave;
	}


	public int sendAddBySection(long baseId,long typeId,List<String> informationList,String loginUserId,String indexName,String sectionId,String infoMark) throws Exception{

		EKnowKnowledgeList eKnowKnowledgeList = new EKnowKnowledgeList();
		eKnowKnowledgeList.setUpdateUserId(loginUserId);
		eKnowKnowledgeList.setTypeId(typeId);

		int isSave = 0;

		//接口入参
		Map<String, Object> sendParams = new HashMap<>();
		sendParams.put("indexName",indexName);
		String sentUrl = URLAPI + "/api/outer/baiDuEKnowAi/putVectorWithDataByList";
		//分批向量化,一次16
		int num = 16;
		for(int i=0;i<informationList.size()+num;i=i+num){
			List<String> newlist = informationList.stream().skip(i).limit(num).collect(Collectors.toList());
			sendParams.put("information",newlist);
			sendParams.put("shardId",sectionId);
			sendParams.put("knowledgeId",infoMark);
			//向量数据库新增向量数据接口
			JSONObject addBack = apiHttpClientUtils.sendHttpPost(sendParams,sentUrl);
			logger.info("返回参数："+addBack);
			if(addBack.get("shardIdList")!=null){
				List<String> shardIdList = (List<String>)addBack.get("shardIdList");
				for(int j=0;j<shardIdList.size();j++){
					eKnowKnowledgeList.setInformation(informationList.get(j+i));
					eKnowKnowledgeList.setESId(shardIdList.get(j));
					eKnowKnowledgeList.setStatus(1);
					eKnowKnowledgeList.setBaseId(baseId);
					eKnowKnowledgeList.setSectionId(sectionId);
					if(infoMark!=null && !"".equals(infoMark)){
						eKnowKnowledgeList.setInfoMark(infoMark);
					}
					int thisSave = eKnowKnowledgeListMapper.insert(eKnowKnowledgeList);
					if(thisSave>0) isSave++;
				}
			}
		}
		return isSave;
	}

	//删除知识库和向量数据库
	@Override
	public int deleteKnowledgeListWithES(long id) throws Exception{
		EKnowKnowledgeList eKnowKnowledgeList = new EKnowKnowledgeList().setId(id).queryFirst();
		int isDel = 0;
		if(eKnowKnowledgeList!=null){
			EKnowKnowledgeBase eKnowKnowledgeBase = new EKnowKnowledgeBase().setId(eKnowKnowledgeList.getBaseId()).queryFirst();
			//接口入参
			Map<String, Object> sendParams = new HashMap<>();
			sendParams.put("indexName",eKnowKnowledgeBase.getESIndexName());
			sendParams.put("shardId",eKnowKnowledgeList.getESId());
			String sentUrl = URLAPI + "/api/outer/baiDuEKnowAi/delKnowledgeList";
			//向量数据库删除向量数据接口
			JSONObject addBack = apiHttpClientUtils.sendHttpPost(sendParams,sentUrl);
			if(addBack.get("shardId")!=null){
				eKnowKnowledgeList.setStatus(1);
				eKnowKnowledgeList.setId(id);
				isDel = eKnowAiDiySqlMapper.deleteKnowledgeList(id);
			}
		}
		return isDel;
	}


	//修改知识库和向量数据库
	@Override
	public int updateKnowledgeListWithES(Map<String, Object> params,String indexName) throws Exception{
		long id = Long.parseLong(params.get("id").toString());//Id
		String loginUserId = ShiroUtils.getUserId();//登录的用户ID
		//long baseId = Long.parseLong(params.get("baseId").toString());//知识库Id
		long typeId = Long.parseLong(params.get("typeId").toString());//所属分类id
		String information = params.get("information").toString();//内容
		int isSave = 0;
		EKnowKnowledgeList eKnowKnowledgeList = new EKnowKnowledgeList();
		eKnowKnowledgeList.setUpdateUserId(loginUserId);
		eKnowKnowledgeList.setTypeId(typeId);
		eKnowKnowledgeList.setStatus(1);
		eKnowKnowledgeList.setId(id);
		EKnowKnowledgeList eKnowKnowledgeListInfo = new EKnowKnowledgeList().setId(id).queryFirst();
		if(eKnowKnowledgeListInfo!=null){
			if(!eKnowKnowledgeListInfo.getInformation().equals(information)){//如果内容有修改
				List<String> informationList = new ArrayList<>();
				informationList.add(information);

				String eSId = eKnowKnowledgeListInfo.getESId();//向量数据库对应id
				//接口入参
				Map<String, Object> sendParams = new HashMap<>();
				sendParams.put("information",informationList);
				sendParams.put("indexName",indexName);
				sendParams.put("shardId",eSId);
				String sentUrl = URLAPI + "/api/outer/baiDuEKnowAi/updateKnowledgeList";
				//向量数据库修改向量数据接口
				JSONObject addBack = apiHttpClientUtils.sendHttpPost(sendParams,sentUrl);
				logger.info("返回参数："+addBack);
				if(addBack.get("shardId")!=null){
					isSave = eKnowKnowledgeListMapper.update(eKnowKnowledgeList);
				}
			}else {//如果内容没有修改
				isSave = eKnowKnowledgeListMapper.update(eKnowKnowledgeList);
			}
		}
		return isSave;
	}



	//分段修改知识库和向量数据库
	@Override
	public int updateKnowledgeListWithESBySection(Map<String, Object> params,String indexName) throws Exception{
		int isSave = 0;
		String sectionId = params.get("sectionId").toString();//分段id
		List<EKnowKnowledgeList> eKnowKnowledgeList = new EKnowKnowledgeList().setSectionId(sectionId).queryList();
		if(eKnowKnowledgeList!=null && eKnowKnowledgeList.size()>0){
			//删除
			for(EKnowKnowledgeList item:eKnowKnowledgeList){
				deleteKnowledgeListWithES(item.getId());
			}
			//新增
			isSave = addKnowledgeListByList(params,indexName);
		}
		return isSave;
	}





	/**
	 * 分段
	 * information信息 ，isRemoveBlank 是否去除连续的空格与换行，0否1是
	 */
	public List<String> splitAndRemoveBlank(String information,String isRemoveBlank){
		List<String> informationList = new ArrayList<>();

		if(isRemoveBlank.equals("1")){
			information = information
					.replaceAll(" +","")  //去空格
					.replaceAll("\\s+", "\n"); //将连续空白字符（包括换行）替换为单个换行
		}

		String[] informationSection = information.split("！");
		//分段
		for(String item : informationSection){
			if(item.length()>300){
				for(int i=0;i<item.length();i=i+300){
					int maxCount = i+300;
					if(i+300>item.length()){
						maxCount = item.length();
					}
					String str1 = item.substring(i,maxCount);
					if(!"".equals(str1.trim())){
						informationList.add(str1);
					}
				}
			}else {
				if(!"".equals(item.trim())){
					informationList.add(item);
				}
			}
		}
		return informationList;
	}
	//去除空格
	public List<String> replaceSpace(List<String> informationList) throws Exception{
		List<String> informationListNew = new ArrayList<>();
		for(String information:informationList){
			information = information
					.replaceAll(" +","")  //去空格
					.replaceAll("\\s+", "\n"); //将连续空白字符（包括换行）替换为单个换行
			informationListNew.add(information);
		}
		return informationListNew;
	}
}
